package chaoyue.study.io.stream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;

/**
 * 文件流
 * FileInputStream 文件读取
 * FileOutputStream 文件写入
 */
public class FileStream {
    public static void main(String[] args) throws Exception {
        // 写入文件
        // 指定输出路径和追加模式(文件不存在会自动创建，但是文件夹一定要存在)
        FileOutputStream fileOutputStream = new FileOutputStream("/Users/chaoyue/Downloads/out.txt");
        fileOutputStream.write("chaoyue hello ".getBytes(StandardCharsets.UTF_8));
        fileOutputStream.flush(); // 清空流 完成写入
        fileOutputStream.close();

        // 读取文件
        StringBuffer stringResult = new StringBuffer();
        FileInputStream fileInputStream = new FileInputStream("/Users/chaoyue/Downloads/out.txt");
        // 使用一个byte数组来接受数据
        byte[] buffer = new byte[8];
        int count = 0;
        int result;
        do {
            count++;
            result = fileInputStream.read(buffer);
            System.out.println("第" + count + "次读取了" + result + "字节，读取到到内容为：" + new String(buffer) + "，剩余" + fileInputStream.available() + "字节");
            if (result != -1) {
                stringResult.append(new String(buffer, 0, result)); //将读取到的结果加入到StringBuffer中
            }
        } while (result != -1); //result为-1表示读取结束
        // 打印读取结果
        System.out.println(stringResult);
        fileInputStream.close();
    }
}
